﻿using System.Collections.Generic;
using System.Threading.Tasks;
using ManageSystem.Repository.Sugar;
using ManageSystem.IRepository;

namespace ManageSystem.Repository
{
    public class BaseRepository<T> : DbContext<T>, IBaseRepository<T> where T : class, new()
    {
        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> Add(T model)
        {
            // 返回受影响行数，判断是否插入成功
            // db is a SqlSugerClient
            long i = await Db.Insertable(model).ExecuteCommandAsync();
            // i is typeof long
            return i > 0;               
        }
        /// <summary>
        /// 根据ID删除(这里是批量删除)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByPrimaryKey(object key)
        {
            // i为删除操作后受影响的行数
            var i = await Db.Deleteable<T>().In(key).ExecuteCommandAsync();
            return i > 0;
        }

        /// <summary>
        /// 根据主键查询一条数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<T> QueryByPrimaryKey(object key)
        {
            // 根据主键查询，返回查询对象
            return await Db.Queryable<T>().InSingleAsync(key);
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> QueryAll()
        {
            // 异步查询对象数组
            return await Db.Queryable<T>().ToListAsync();

        }

        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> Update(T model)
        {
            //这种方式会以model中主键的值为条件进行更新
            var i = await Db.Updateable(model).ExecuteCommandAsync();
            return i > 0;
        }
    }
}
